<template>
	<view>
		<image :src="base.service_image" class="w-750 h-668 scrollView"></image>
		<!-- app -->
		<!-- #ifdef APP-PLUS -->
		<view class="position-fixed left-0 right-0 title-box  c-white">
			<view class="p-t-60 d-flex-items-center d-flex-between">
				<view class="w-100 p-l-30" @click="$jump.navigateBack()">
					<u-icon name="arrow-left" color="#ffffff" size="42"></u-icon>
				</view>
				<view class="f-36">标的详情</view>
				<view class="w-100"></view>
			</view>
		</view>
		<!-- #endif -->
		<view class="position-fixed left-0 right-0  bgc-box">
			<scroll-view scroll-y="true" :style="{height:scrollHeight+'px'}">
				<view class="bgc-white m-t-40 m-b-25 m-l-40 m-r-40 br-30 p-t-25 p-b-25 p-l-32 p-r-32">
					<view class="c-F85639 f-36">
						<text class="f-24">预付款：￥</text>{{base.service_price}}
					</view>
					<view class="m-t-8 m-b-8 f-32 font-weight-bold">{{base.category_name}}</view>
					<view class="">标的规格：{{base.service_unit}}</view>
				</view>
				<view class="bgc-white br-30 m-l-40 m-r-40 w-670 p-t-24 p-l-34 p-r-34">
					<view>
						<u-icon name="bookmark-fill" color="#A7B4C4" size="32"></u-icon>
						<text class="f-32 c-33 m-l-15 font-weight-bold">详情</text>
					</view>
					<view class="font-weight-bold m-t-25 m-b-16">整体图</view>
					<view class="d-flex-between d-flex-wrap p-b-25">
						<view class="align-center" v-for="(item,index) in efect_list" :key="index">
							<image :src="item.efect_image" class="w-180 h-132"
								@click="previewImage(item.efect_image, efect_list, index)"></image>
							<view class="c-33 f-24 m-t-8">{{item.efect_name}}</view>
						</view>
					</view>
					<view class="b-t"></view>
					<view class="font-weight-bold m-t-25 m-b-16">施工图</view>
					<view class="d-flex-between d-flex-wrap p-b-25">
						<view class="align-center" v-for="(item,index) in construction_list" :key="index">
							<image :src="item.construction_image" class="w-132 h-132"
								@click="previewImage(item.construction_image, construction_list, index)"></image>
							<view class="c-33 f-24 m-t-8">{{item.construction_name}}</view>
						</view>
					</view>
					<view v-if="base.show_price == 1">
						<view class="b-t"></view>
						<view class="font-weight-bold m-t-25 m-b-16">地基核价</view>
						<view class=" d-flex d-flex-wrap d-flex-between">
							<view class="item d-flex-items-center d-flex-between p-l-20 p-r-20 m-b-25"
								v-for="(item,index) in pricing_list" :key="index">
								<view class="w-180 f-24 c-33">
									{{item.pricing_name}}{{item.pricing_price}}/{{item.pricing_unit}}</view>
								<view class="item-bgc align-center">
									<input type="number" v-model="item.number">
								</view>
							</view>
						</view>
						<view class="d-flex-items-center d-flex-between">
							合计：
							<view class="heng"></view>
							<view class="c-F85639 f-36">
								<text class="f-24">￥</text>{{totalPrice}}
							</view>
						</view>
					</view>
					
					<view v-if="base.show_tig_price == 1">
						<view class="b-t"></view>
						<view class="font-weight-bold m-t-25 m-b-16">设施安装合价</view>
						<view class=" d-flex d-flex-wrap d-flex-between">
							<view class="item d-flex-items-center d-flex-between p-l-20 p-r-20 m-b-25"
								v-for="(item,index) in rig_pricing_list" :key="index">
								<view class="w-180 f-24 c-33">
									{{item.pricing_name}}</view>
								<view class="item-bgct align-center">
									<input type="number" v-model="item.pricing_price">
								</view>
							</view>
						</view>
					</view>
					
					
				</view>

			</scroll-view>
			<view class="align-center m-t-10 h-40 d-flex-items-center d-flex-center" @click="agree = !agree">
				<u-icon name="checkmark-circle-fill" :color="agree ? '#5C65FF':'#999999'" size="34"
					class="m-r-10"></u-icon>
				阅读并同意<text class="c-5C65FF"
					@click.stop="$jump.navigateTo('/pages/login/agree?title=服务协议')">《用户服务协议》</text>
			</view>
			<view
				class="w-750 h-160 bgc-white bottom position-fixed left-0 right-0 bottom-0 d-flex-items-center d-flex-between p-l-90 p-r-40">
				<view class="align-center" @click="contactService">
					<image src="https://www.shuyunpt.com/app/image//shop/Vector@2x.png" class="w-40 h-40"></image>
					<view class="f-20">客服</view>
				</view>
				<view class="w-400 h-80 position-retive" @click="submit">
					<image src="https://www.shuyunpt.com/app/image//shop/Rectangle_159.png" class="w-400 h-80"></image>
					<view class="position-absolute left-0 right-0 top-0 bottom-0 d-flex-items-center d-flex-center c-white f-32 font-weight-bold">付款下单</view>
				</view>
			</view>
		</view>
		<u-popup v-model="show" mode="bottom" border-radius="20">
			<view class="popup-content">
				<view class="popup-header">
					<view class="popup-title">确认订单</view>
					<view class="popup-close" @click="show = false">
						<u-icon name="close" color="#999999" size="32"></u-icon>
					</view>
				</view>

				<view class="popup-body">
					<!-- 服务时间 -->
					<view class="form-item">
						<view class="form-label">服务时间</view>
						<view class="form-input" @click="openTimePicker">
							<text class="input-text">{{timer ? timer : '请选择今天或以后的日期'}}</text>
							<u-icon name="arrow-right" color="#999999" size="24"></u-icon>
						</view>
						<view class="form-tip">只能选择今天及以后的日期</view>
					</view>

					<!-- 收货地址 -->
					<view class="form-item">
						<view class="form-label">收货地址</view>
						<view class="form-input" @click="$jump.navigateTo('/pages/address/address?type=1&id=' + id)">
							<text class="input-text">点击选择收货地址</text>
							<u-icon name="arrow-right" color="#999999" size="24"></u-icon>
						</view>
					</view>

					<!-- 地址信息 -->
					<view v-if="addressInfo.address_id" class="address-info">
						<view class="address-header">
							<text class="contact-name">{{addressInfo.contact_name}}</text>
							<text class="contact-phone">{{addressInfo.contact_phone}}</text>
						</view>
						<view class="address-detail">
							{{addressInfo.province}}{{addressInfo.city}}{{addressInfo.district}}{{addressInfo.detail_address}}
						</view>
					</view>

					<!-- 未选择地址提示 -->
					<view v-else class="no-address">
						<text class="no-address-text">您还未添加收货地址</text>
					</view>
				</view>

				<view class="popup-footer">
					<button class="confirm-btn" @click="sureOrder" :disabled="isSubmitting">
						<view v-if="isSubmitting" class="loading-content">
							<u-icon name="loading" color="#ffffff" size="24" class="loading-icon"></u-icon>
							<text class="loading-text">创建中...</text>
						</view>
						<text v-else>确认下单</text>
					</button>
				</view>
			</view>
		</u-popup>
		<u-picker v-model="timeShow" mode="time" :start-year="currentYear" :start-month="currentMonth"
			:start-day="currentDay" :end-year="currentYear + 10" @confirm="confirm"></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			const today = new Date();
			return {
				id: "",
				scrollHeight: 0,
				base: {},
				efect_list: [],
				construction_list: [],
				pricing_list: [],
				rig_pricing_list: [],
				agree: false,
				show: false,
				timer: "",
				addressInfo: {},
				timeShow: false,
				isSubmitting: false, // 提交状态
				currentYear: today.getFullYear(),
				currentMonth: today.getMonth() + 1,
				currentDay: today.getDate()
			}
		},
		onReady() {
			let _this = this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					let wHeight = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					let titleH = uni.createSelectorQuery().select(".scrollView"); //想要获取高度的元素名（class/id）
					titleH.boundingClientRect(data => {
						_this.scrollHeight = wHeight - data.height - 40
					}).exec()
				}
			})
		},
		computed: {
			totalPrice() {
				console.log(this.pricing_list)
				let data = this.pricing_list.reduce((item, val) => {
					return item + (val.number * val.pricing_price)

				}, 0)
				return data
			},
		},
		onLoad(params) {
			this.getInfo(params.id)
			this.id = params.id

			// 设置默认服务时间为明天
			this.setDefaultServiceTime();
		},
		onShow() {
			let _this = this;
			uni.$once('updateAdressId', function(data) {
				_this.addressInfo = JSON.parse(data)
			})
		},
		methods: {
			// 设置默认服务时间
			setDefaultServiceTime() {
				const tomorrow = new Date();
				tomorrow.setDate(tomorrow.getDate() + 1);
				this.timer =
					`${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}`;
			},

			// 获取当前日期信息
			getCurrentDateInfo() {
				const today = new Date();
				return {
					year: today.getFullYear(),
					month: today.getMonth() + 1,
					day: today.getDate()
				};
			},

			// 打开时间选择器
			openTimePicker() {
				// 更新当前日期信息，确保限制是最新的
				const currentDate = this.getCurrentDateInfo();
				this.currentYear = currentDate.year;
				this.currentMonth = currentDate.month;
				this.currentDay = currentDate.day;

				// 打开时间选择器
				this.timeShow = true;
			},
			async contactService() {
				console.log(this.orderNo);
				const res = await this.$service({
					url: "/api/member.message/startServiceChat",
				})
				console.log(res);
				uni.navigateTo({
					url: `/pages/notice/message?name=客服&message_id=${res.data.message_id}`
				})
			},
			async sureOrder() {
				if (!this.timer) return this.$hint.desc('请选择服务时间')
				if (!this.addressInfo.address_id) return this.$hint.desc('请选择收货地址')

				// 防止重复提交
				if (this.isSubmitting) return;
				this.isSubmitting = true;

				// 显示加载提示
				this.$hint.showLoading('正在提交订单...');

				let data = {
					service_id: this.id,
					address_id: this.addressInfo.address_id,
					service_time: this.timer,
					service_pricing: JSON.stringify(this.pricing_list),
					rig_pricing_list: JSON.stringify(this.rig_pricing_list)
				}
				console.log(data);

				try {
					const res = await this.$service({
						url: "/api/member.service/confirmServiceOrder",
						data: {
							...data
						}
					})
					console.log(res);

					// 隐藏加载提示
					this.$hint.hideLoading();

					if (res.code == 1) {
						this.$hint.desc('订单创建成功');

						// 关闭弹窗
						this.show = false;

						if (res.data.is_pay == 1) {
							// 跳转到订单详情页
							setTimeout(() => {
								uni.navigateTo({
									url: `/pages/order/detail?order=${res.data.order_no}`
								});
							}, 1000);
						} else {
							// 根据平台环境处理支付
							// #ifdef MP-WEIXIN
							// 微信小程序环境下直接调用支付接口
							await this.wechatPay(res.data);
							// #endif

							// #ifdef APP-PLUS
							// APP环境下跳转到支付页面
							const orderInfo = {
								order_id: res.data.order_id,
								order_no: res.data.order_no,
								total_amount: res.data.total_amount,
								service_name: this.base.category_name
							};
							// 跳转到支付页面
							setTimeout(() => {
								uni.navigateTo({
									url: `/pages/pay/index?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}`
								});
							}, 1000);
							// #endif
						}

					} else {
						this.$hint.desc(res.msg || '订单创建失败');
					}
				} catch (error) {
					// 隐藏加载提示
					this.$hint.hideLoading();
					console.error('订单创建失败:', error);
					this.$hint.desc('订单创建失败，请重试');
				} finally {
					// 重置提交状态
					this.isSubmitting = false;
				}
			},
			confirm(e) {
				console.log(e);

				// 检查选择的日期是否为今天或以后
				const selectedDate = new Date(e.year, e.month - 1, e.day);
				const today = new Date();
				today.setHours(0, 0, 0, 0); // 设置时间为00:00:00，只比较日期

				if (selectedDate < today) {
					this.$hint.desc('服务时间不能选择今天之前的日期');
					return;
				}

				// 格式化日期，确保月份和日期是两位数
				const formattedMonth = String(e.month).padStart(2, '0');
				const formattedDay = String(e.day).padStart(2, '0');
				this.timer = `${e.year}-${formattedMonth}-${formattedDay}`;
			},
			submit() {
				if (!this.agree) return this.$hint.desc('请阅读并同意《用户服务协议》')

				// 检查登录状态
				// const userInfo = uni.getStorageSync('userInfo');
				// if (!userInfo || !userInfo.token) {
				// 	// 未登录，跳转到登录页面并记录来源
				// 	const currentUrl = '/pages/shops/detail';
				// 	const currentParams = {
				// 		id: this.id
				// 	};
				// 	uni.navigateTo({
				// 		url: `/pages/login/index?source_url=${encodeURIComponent(currentUrl)}&source_params=${encodeURIComponent(JSON.stringify(currentParams))}`
				// 	});
				// 	return;
				// }

				this.show = true
				this.getAddress()
			},
			async getAddress() {
				const res = await this.$service({
					url: "/api/member.user/getUserAddress",
					method: "GET"
				})
				console.log(res)
				// 不设置默认地址，让用户手动选择
				this.addressInfo = {}
			},
			async getInfo(id) {
				try {
					// 显示加载提示
					this.$hint.showLoading('加载中...');

					const res = await this.$service({
						url: "/api/member.service/getServiceInfo",
						data: {
							service_id: id
						}
					})
					console.log(res);

					// 隐藏加载提示
					this.$hint.hideLoading();

					this.base = res.data.base
					this.efect_list = res.data.efect_list
					this.construction_list = res.data.construction_list
					this.pricing_list = res.data.pricing_list.map(item => {
						return {
							pricing_id: item.pricing_id,
							pricing_name: item.pricing_name,
							number: item.number || 0,
							pricing_price: item.pricing_price,
							pricing_unit: item.pricing_unit
						}
					})
					this.rig_pricing_list = res.data.rig_pricing_list.map(item => {
						return {
							pricing_id: item.pricing_id,
							pricing_name: item.pricing_name,
							pricing_price: 0,
						}
					})
					
				} catch (error) {
					// 隐藏加载提示
					this.$hint.hideLoading();
					console.error('获取商品信息失败:', error);
					this.$hint.desc('获取商品信息失败，请重试');
				}
			},

			// 微信小程序支付
			async wechatPay(orderData) {
				try {
					this.$hint.showLoading('正在发起支付...');

					// 调用支付接口
					const res = await this.$service({
						url: '/api/member.pay/payOrder',
						data: {
							order_no: orderData.order_no,
							pay_type: 'wx_min'
						}
					});

					this.$hint.hideLoading();

					if (res.code === 1) {
						// 发起微信支付
						uni.requestPayment({
							timeStamp: res.data.timeStamp,
							nonceStr: res.data.nonceStr,
							package: res.data.package,
							signType: res.data.signType,
							paySign: res.data.paySign,
							success: (payRes) => {
								console.log('支付成功:', payRes);
								this.$hint.desc('支付成功');
								// 跳转到订单详情页
								setTimeout(() => {
									uni.navigateTo({
										url: `/pages/order/detail?order=${orderData.order_no}`
									});
								}, 1000);
							},
							fail: (payErr) => {
								console.log('支付失败:', payErr);
								if (payErr.errMsg.includes('cancel')) {
									this.$hint.desc('支付已取消');
								} else {
									this.$hint.desc('支付失败，请重试');
								}
							}
						});
					} else {
						this.$hint.desc(res.msg || '支付发起失败');
					}
				} catch (error) {
					this.$hint.hideLoading();
					console.error('支付失败:', error);
					this.$hint.desc('支付失败，请重试');
				}
			},
			// 图片预览
			previewImage(url, list, index) {
				// 根据列表类型确定图片字段名
				let imageField = 'efect_image';
				if (list === this.construction_list) {
					imageField = 'construction_image';
				}

				uni.previewImage({
					current: url,
					urls: list.map(item => item[imageField])
				});
			}
		}
	}
</script>



<style>
	page {
		background: #F6F8F9;
	}
</style>
<style scoped>
	.bgc-box {
		background: #F6F8F9;
		border-radius: 60rpx 60rpx 0rpx 0rpx;
		top: 520rpx;
	}

	.c-F85639 {
		color: #F85639;
	}

	.item {
		width: 290rpx;
		height: 56rpx;
		background: #B1D5FF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
	}

	.item-bgc {
		width: 84rpx;
		height: 40rpx;
		background: #FFFFFF;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		border: 2rpx solid #FFFFFF;
	}
	.item-bgct {
		width: 154rpx;
		height: 40rpx;
		background: #FFFFFF;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		border: 2rpx solid #FFFFFF;
	}
	.heng {
		width: 320rpx;
		height: 0rpx;
		border: 1rpx solid #777777;
	}

	.bottom {
		box-shadow: 0rpx -8rpx 40rpx 0rpx rgba(167, 180, 196, 0.2);
		border-radius: 60rpx 60rpx 0rpx 0rpx;
	}

	.c-5C65FF {
		color: #5C65FF;
	}

	.title-box {
		top: var(--status-bar-height);
	}

	.confirm-btn {
		width: 100%;
		height: 88rpx;
		background-color: #5C65FF;
		color: #ffffff;
		font-size: 32rpx;
		font-weight: bold;
		border-radius: 44rpx;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.confirm-btn::after {
		border: none;
	}

	.confirm-btn:active {
		background-color: #4A52E8;
	}

	.confirm-btn:disabled {
		background-color: #cccccc;
		opacity: 0.7;
	}

	.loading-content {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading-icon {
		margin-right: 10rpx;
		animation: rotate 1s linear infinite;
	}

	.loading-text {
		font-size: 28rpx;
		color: #ffffff;
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	/* 弹窗样式 */
	.popup-content {
		background: #ffffff;
		border-radius: 24rpx 24rpx 0 0;
		overflow: hidden;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.popup-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx 40rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		background: linear-gradient(135deg, #5C65FF 0%, #4A52E8 100%);
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #ffffff;
	}

	.popup-close {
		padding: 15rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.2);
	}

	.popup-body {
		padding: 40rpx;
		max-height: 65vh;
		overflow-y: auto;
		background: #ffffff;
	}

	.form-item {
		margin-bottom: 50rpx;
	}

	.form-label {
		font-size: 30rpx;
		color: #333333;
		font-weight: 600;
		margin-bottom: 25rpx;
		display: flex;
		align-items: center;
	}

	.form-label::before {
		content: '';
		width: 6rpx;
		height: 30rpx;
		background: #5C65FF;
		border-radius: 3rpx;
		margin-right: 15rpx;
	}

	.form-input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 35rpx;
		background: #f8f9fa;
		border-radius: 16rpx;
		border: 2rpx solid #e9ecef;
		transition: all 0.3s ease;
	}

	.form-input:active {
		background: #f0f0f0;
		border-color: #5C65FF;
	}

	.input-text {
		font-size: 28rpx;
		color: #666666;
		flex: 1;
	}

	.form-tip {
		font-size: 24rpx;
		color: #999999;
		margin-top: 10rpx;
		padding-left: 10rpx;
	}

	.address-info {
		background: linear-gradient(135deg, #f8f9fa 0%, #f0f0f0 100%);
		border-radius: 16rpx;
		padding: 35rpx;
		margin-top: 25rpx;
		border: 2rpx solid #e9ecef;
		position: relative;
	}

	.address-info::before {
		content: '';
		position: absolute;
		left: 0;
		top: 0;
		bottom: 0;
		width: 6rpx;
		background: #5C65FF;
		border-radius: 0 3rpx 3rpx 0;
	}

	.address-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.contact-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-right: 30rpx;
	}

	.contact-phone {
		font-size: 28rpx;
		color: #666666;
		background: #e9ecef;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
	}

	.address-detail {
		font-size: 28rpx;
		color: #666666;
		line-height: 1.6;
		padding: 20rpx 0;
	}

	.no-address {
		text-align: center;
		padding: 60rpx 0;
		background: #f8f9fa;
		border-radius: 16rpx;
		border: 2rpx dashed #e9ecef;
	}

	.no-address-text {
		font-size: 28rpx;
		color: #999999;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.no-address-text::before {
		content: '📍';
		margin-right: 10rpx;
		font-size: 32rpx;
	}

	.popup-footer {
		padding: 40rpx;
		border-top: 1rpx solid #f0f0f0;
		background: #ffffff;
	}

	/* 图片点击样式 */
	.w-180.h-132,
	.w-132.h-132 {
		cursor: pointer;
		transition: transform 0.2s ease;
	}

	.w-180.h-132:active,
	.w-132.h-132:active {
		transform: scale(0.95);
	}

	/* 添加图片点击提示 */
	.align-center {
		position: relative;
	}

	.align-center::after {
		position: absolute;
		top: 5rpx;
		right: 5rpx;
		font-size: 20rpx;
		background: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 50%;
		width: 30rpx;
		height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0.8;
	}
</style>